/**
 * @(#) WxSupportUtil.java    2015/07/14 10:38
 *
 * 版权所有 (c) 山东远洋网络科技有限公司
 * 保留所有权利
 */
package com.banksoft.front.util;



import com.banksoft.admin.bean.Group;
import com.banksoft.admin.bean.WeiXinMenu;
import com.banksoft.admin.bean.WxSetting;
import com.banksoft.front.bean.QrBack;
import com.banksoft.front.bean.TicketMessage;
import com.banksoft.front.bean.TokenMessage;
import com.banksoft.front.bean.WeiXinUser;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建查询删除自定义菜单以及接受消息发送消息
 *
 * @author 张战军
 * @version 1.0
 */
public class WxSupportUtil {
    private static Logger logger = LoggerFactory.getLogger(WxSupportUtil.class);

    private static String createMenu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";//创建自定义菜单
    private static String accessToken_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";//获取access_token
    private static String getMenu_url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";//获取菜单
    private static String deleteMenu_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=";//删除自定义菜单
    private static String getGroupByUserId_url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=";//查询用户所在分组
    private static String getGZOpenId_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=";//获取关注者列表
    private static String getWeiXinUser_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=";//获取用户基本信息
    private static String getWeiXinUserList_url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=";//批量获取用户基本信息
    private static String getWeiXinGroup_url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=";//获取用户组列表
    private static String createGroup_url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=";//创建用户组
    private static String updateGroupName_url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=";//修改用户组名
    private static String moveUserToGroup_url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=";//移动用户分组
    private static String createQrCode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";//申请二维码
    private static String uploadImage_url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=";  //上传多媒体文件
    private static String kfSendMessage_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";//客服接口发送消息
    public static String SEND_TEMPLATE_MESSAGE="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";//模板消息

    private static String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi";//获取jsapi_ticket
    private static String group_send_mes_url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=";//根据分组进行群发消息
    private static String upload_media_url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=";//群发消息时上传图文消息素材
    private static String tyZf_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//统一支付接口

    private static Map<String, TokenMessage> tokenMessageMap = new HashMap<String, TokenMessage>();//第一次获取token的时候存到该静态变量中，下次获取的时候判断与上次获取的token的时间对比是否在有效期
                                                                //内，如果超过有效期则重新获取，如果没有超过有效期则不用重新获取


    //获取用户基本信息
    public static WeiXinUser getWeiXinUser(String openid, WxSetting weiXinSetting) throws IOException {
        String url = getWeiXinUser_url + createAccess_token(weiXinSetting);
        String data = "openid=" + openid + "&lang=zh_CN";
        String jsonString = ResponseUtil.requestByPost(url, data);
        WeiXinUser weiXinUser = (WeiXinUser) JSONHelper.fromJson(jsonString, WeiXinUser.class);
        return weiXinUser;
    }

    //创建菜单
    public static TokenMessage createMenu(WeiXinMenu weiXinMenu, WxSetting weiXinSetting) throws IOException {
        //String jsonData = "{\"button\":[{\"type\":\"view\",\"name\":\"MENU01\",\"url\":\"http://baidu.com/\"},{\"type\":\"click\",\"name\":\"天气查询\",\"key\":\"tianQi\"},{\"name\":\"日常工作\",\"sub_button\":[{\"type\":\"click\",\"name\":\"待办工单\",\"key\":\"01_WAITING\"},{\"type\":\"click\",\"name\":\"已办工单\",\"key\":\"02_FINISH\"},{\"type\":\"click\",\"name\":\"我的工单\",\"key\":\"03_MYJOB\"},{\"type\":\"click\",\"name\":\"公告消息箱\",\"key\":\"04_MESSAGEBOX\"},{\"type\":\"click\",\"name\":\"签到\",\"key\":\"05_SIGN\"}]}]}";
        String jsonData = JSONHelper.toJson(weiXinMenu);//把自定义菜单转成json字符串
        logger.info(jsonData);
        deleteMenu(weiXinSetting);
        jsonData = ZyUnicodeUtil.ascii2Native(jsonData);
        String url = createMenu_url + createAccess_token(weiXinSetting) ;//组装路径
        String resultJson = ResponseUtil.requestByPost(url, jsonData);
        TokenMessage tokenMessage = (TokenMessage) JSONHelper.fromJson(resultJson, TokenMessage.class);
        return tokenMessage;
    }

    //查找菜单
    public static String findMenu( WxSetting weiXinSetting) throws IOException {
        String url = getMenu_url + createAccess_token(weiXinSetting);
        String resultJson = ResponseUtil.requestByPost(url, "");
        return resultJson;
    }


    //删除菜单
    public static TokenMessage deleteMenu(WxSetting weiXinSetting) throws IOException {
        String url = deleteMenu_url  + createAccess_token(weiXinSetting);
        String resultJson = ResponseUtil.requestByPost(url, "");
        TokenMessage tokenMessage = (TokenMessage) JSONHelper.fromJson(resultJson, TokenMessage.class);
        return tokenMessage;
    }

    //上传图片到微信服务器
    public static String uploadImageToWeiXin(String type, WxSetting weiXinSetting, String imagePath) throws Exception {
        String url = uploadImage_url + createAccess_token(weiXinSetting) + "&type=" + type;
        File file = ResponseUtil.getImageFromNet(imagePath);
        if(file == null || file.length() == 0) {
            return null;
        }
        String jsonString = ResponseUtil.uploadImage(url, file);
        Map<String, Object> map = (Map<String, Object>) JSONHelper.fromJson(jsonString, HashMap.class);
        if(map.get("media_id") != null) {
            return map.get("media_id").toString();
        }
        return null;
    }

    //获取所有用户分组
    public static List<Group> getGroupList(WxSetting weiXinSetting) throws IOException {
        String url = getWeiXinGroup_url + createAccess_token(weiXinSetting);
        String jsonString = ResponseUtil.requestByPost(url, "");
        Map<String, Object> map = (Map<String, Object>) JSONHelper.fromJson(jsonString, HashMap.class);
        if(map.get("groups") != null) {
            List<Group> groupList = (List<Group>) JSONHelper.fromJson(map.get("groups").toString(), new TypeToken<List<Group>>() {
            }.getType());
            return groupList;
        } else {
            return new ArrayList<Group>();
        }
    }

    //获取access_token
    public static  String createAccess_token(WxSetting weiXinSetting) throws IOException {
        return WeixinUtil.getAccessToken(weiXinSetting);
    }

    //重新获取token
    private static TokenMessage getTokenMessage(WxSetting weiXinSetting) throws IOException {
        String url_1 = accessToken_url + "&appid=" + weiXinSetting.getAppId() + "&secret=" + weiXinSetting.getAppSecret();
        String resultJson = ResponseUtil.requestByPost(url_1, "");
        TokenMessage tokenMessage = (TokenMessage) JSONHelper.fromJson(resultJson, TokenMessage.class);
        tokenMessage.setCreateTime(System.currentTimeMillis());
        tokenMessageMap.put(weiXinSetting.getAppId(), tokenMessage);
        return tokenMessage;
    }

    //获取jsapi_ticket
    public static String createJsapi_ticket(String access_Token) throws IOException {
        String url = jsapi_ticket_url + "&access_token=" + access_Token;
        String resultJson = ResponseUtil.requestByPost(url, "");
        TicketMessage ticketMessage = (TicketMessage) JSONHelper.fromJson(resultJson, TicketMessage.class);
        return ticketMessage.getTicket();
    }

    //群发消息
    public static String sendGroupMes(WxSetting weiXinSetting, String sendMes) throws IOException {
        String url = group_send_mes_url + createAccess_token(weiXinSetting);
        String jsonString = ResponseUtil.requestByPost(url, sendMes);
        return jsonString;
    }

    //上传图文素材
    public static String uploadMedia(WxSetting weiXinSetting, String articlesXml) throws IOException {
        String url = upload_media_url + createAccess_token(weiXinSetting);
        String jsonString = ResponseUtil.requestByPost(url, articlesXml);
        return jsonString;
    }

    //客服接口发送消息
    public static String kfSendMessage(WxSetting WeixinSet, String sendMes) throws IOException {
        String url = kfSendMessage_url + createAccess_token(WeixinSet);
        String jsonString = ResponseUtil.requestByPost(url, sendMes);
        return jsonString;
    }

    //发送模板消息
    public static String templateMessage(WxSetting setting, String data) throws IOException {
        String url = SEND_TEMPLATE_MESSAGE + createAccess_token(setting);
        String jsonString = ResponseUtil.requestByPost(url, data);
        return jsonString;
    }

    //网页授权获取access_token
    public static String getSqAccessTokenByCode(String code, WxSetting weiXinSetting) throws IOException {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" + "?appid=" + weiXinSetting.getAppId();
        String data = "&secret="  + weiXinSetting.getAppSecret()+ "&code=" + code + "&grant_type=authorization_code";
        String jsonString = ResponseUtil.requestByPost(url, data);
        return jsonString;
    }

    //查找
    public static QrBack qr( WxSetting weiXinSetting, String scene_str) throws IOException {
        String url = createQrCode_url + createAccess_token(weiXinSetting);
        //String data = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+scene_str+"\"}}}";
        String data = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+scene_str+"\"}}}";
        String resultJson = ResponseUtil.requestByPost(url, data);
        System.out.println("获取唯一码返回：：：  "+resultJson);
        QrBack qrBack = (QrBack) JSONHelper.fromJson(resultJson, QrBack.class);
        return qrBack;
    }


}
